package com.leave.web.servlet;

import com.leave.context.AppContext;
import com.leave.entity.Course;
import com.leave.service.CourseService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "CourseServlet", urlPatterns = {"/course"})
public class CourseServlet extends HttpServlet {

    private final static String COURSE_LIST = "/WEB-INF/views/instructor/instructor_course.jsp";

    private final Logger logger = LoggerFactory.getLogger(LeaveServlet.class);

    private CourseService courseService;
    @Override
    public void init() throws ServletException {
        super.init();
        //从IoC容器获取实例化bean组件
        courseService = AppContext.getBean(CourseService.class);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        HttpSession session = request.getSession();
        logger.info("request process starting" + action);
        String courseID = request.getParameter("courseID");
        String classID = request.getParameter("classID");
        String courseName = request.getParameter("courseName");
        String year = request.getParameter("year");
        String term = request.getParameter("term");
        String hour = request.getParameter("hour");
        String keyword = request.getParameter("keyword");
        try {
            //2:调用userService完成处理,此处switch语句的语法要求jdk1.8以上。
            switch (action) {
                case "list":
                    List<Course> courseList = courseService.listcourse(null);
                    session.setAttribute("list", courseList);
                    request.getRequestDispatcher(COURSE_LIST).forward(request, response);
                    break;
                case "seek":
                    try {
                        List<Map<String, Object>> courseList1 = courseService.seekCourse(keyword);
//                        System.out.println("查询到："+courseList1);
                        // 将查询结果传递给前端进行展示
                        session.setAttribute("list", courseList1);
                        request.getRequestDispatcher(COURSE_LIST).forward(request, response);
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    break;
                case "delete":
                    boolean successD = courseService.deleteCourse(courseID);
                    if (successD) {
                        // 表单提交成功
                        request.setAttribute("successMessage", "课程信息成功！");
                    } else {
                        // 数据写入失败
                        request.setAttribute("errorMessage", "课程信息失败，请重试！");
                    }
                    request.getRequestDispatcher("course?action=list").forward(request, response);
                    break;
                case "add":
                    Course course = new Course();
                    //接收表单(Form)参数,并转换为实体对象的属性值
                    resolveRequestParameter(request,course);
                    //调用service组件完成数据写入
                    boolean successA = courseService.addCourse(course);
                    if (successA) {
                        // 表单提交成功
                        request.setAttribute("successMessage", "课程添加成功！");
                    } else {
                        // 数据写入失败
                        request.setAttribute("errorMessage", "课程添加失败，请重试！");
                    }
                    //指定跳转路径
                    request.getRequestDispatcher("course?action=list").forward(request, response);
                    break;
                case "edit":
                    Course course_1 = new Course();
                    //接收表单(Form)参数,并转换为实体对象的属性值
                    resolveRequestParameter(request,course_1);
                    //调用service组件完成数据写入
                    boolean successE = courseService.editCourse(course_1);
                    if (successE) {
                        // 表单提交成功
                        request.setAttribute("successMessage", "课程信息修改成功！");
                    } else {
                        // 数据写入失败
                        request.setAttribute("errorMessage", "课程信息修改失败，请重试！");
                    }
                    request.getRequestDispatcher("course?action=list").forward(request, response);
                    break;
            }

        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    private void resolveRequestParameter(HttpServletRequest req, Object bean) {
        Map<String, String[]> reqParameterMap = req.getParameterMap();
//        System.out.println("reqParameterMap+" + reqParameterMap);
        Map<String, String[]> propertiesMap = new HashMap<String, String[]>();
        try {
            for (Map.Entry<String, String[]> entry : reqParameterMap.entrySet()) {
                String name = entry.getKey();
                String[] values = entry.getValue();
                // 判断 request 参数是否对应 JavaBean 对象的属性
                Class<?> propertyType = PropertyUtils.getPropertyType(bean, name);
                if (propertyType != null) {
                    propertiesMap.put(name, values);
                }
            }
            // 转换为 POJO 对象 bean 的属性值
            BeanUtils.populate(bean, propertiesMap);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("The property name could not be found", e);
        }
    }
}
